package com.ruoyi.dev.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.PageResult;
import com.ruoyi.base.domain.BaseDocument;
import com.ruoyi.base.domain.BaseMetaSpace;
import com.ruoyi.base.domain.BaseSubject;
import com.ruoyi.base.service.IBaseMetaSpaceService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.dev.domain.DevModel;
import com.ruoyi.dev.service.IDevModelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.dev.mapper.DevValidationMapper;
import com.ruoyi.dev.domain.DevValidation;
import com.ruoyi.dev.service.IDevValidationService;

import javax.sql.DataSource;

/**
 * 数据验证Service业务层处理
 * 
 * @author yepanpan
 * @date 2025-02-25
 */
@Service
public class DevValidationServiceImpl implements IDevValidationService 
{
    private static final Logger log = LoggerFactory.getLogger(DevValidationServiceImpl.class);

    @Autowired
    private DevValidationMapper devValidationMapper;
    @Autowired
    private IDevModelService devModelService;
    @Autowired
    private IBaseMetaSpaceService baseMetaSpaceService;
    @Autowired
    private DataSource dataSource;

    /**
     * 查询数据验证
     * 
     * @param id 数据验证主键
     * @return 数据验证
     */
    @Override
    public DevValidation selectDevValidationById(Long id)
    {
        return devValidationMapper.selectDevValidationById(id);
    }

    /**
     * 查询数据验证列表
     * 
     * @param devValidation 数据验证
     * @return 数据验证
     */
    @Override
    public List<DevValidation> selectDevValidationList(DevValidation devValidation)
    {
        return devValidationMapper.selectDevValidationList(devValidation);
    }

    /**
     * 新增数据验证
     * 
     * @param devValidation 数据验证
     * @return 结果
     */
    @Override
    public int insertDevValidation(DevValidation devValidation)
    {
        devValidation.setCreateTime(DateUtils.getNowDate());
        return devValidationMapper.insertDevValidation(devValidation);
    }

    /**
     * 修改数据验证
     * 
     * @param devValidation 数据验证
     * @return 结果
     */
    @Override
    public int updateDevValidation(DevValidation devValidation)
    {
        devValidation.setUpdateTime(DateUtils.getNowDate());
        return devValidationMapper.updateDevValidation(devValidation);
    }

    /**
     * 批量删除数据验证
     * 
     * @param ids 需要删除的数据验证主键
     * @return 结果
     */
    @Override
    public int deleteDevValidationByIds(Long[] ids)
    {
        return devValidationMapper.deleteDevValidationByIds(ids);
    }

    /**
     * 删除数据验证信息
     * 
     * @param id 数据验证主键
     * @return 结果
     */
    @Override
    public int deleteDevValidationById(Long id)
    {
        return devValidationMapper.deleteDevValidationById(id);
    }

    /**
     * 验证指定模型的数据
     *
     * @param modelId 数据模型的主键
     * @return 数据验证结果
     */
    @Override
    public String validateModelData(Long modelId){
        DevModel devModel = devModelService.selectDevModelDetail(modelId);
        if(devModel == null){
            return "数据模型不存在";
        }
        DevValidation vc = new DevValidation();
        vc.setModelId(modelId);
        List<DevValidation> validationList = devValidationMapper.selectDevValidationList(vc);
        if(validationList == null || validationList.isEmpty()){
            return "数据模型没有配置验证规则";
        }

        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        Map<String, String> metaMap = new HashMap<>();
        Db db = Db.use(dataSource);

        try {
            //先执行自定义查询验证
            for(DevValidation validation:validationList){
                if(!validation.getType().equals(DevValidation.TYPE_SQL)){
                    continue;
                }
                List<Entity> list = db.query(validation.getSqls());
                if(list == null || list.isEmpty()){
                    continue;
                }
                for(Entity row:list){
                    failureNum ++;
                    failureMsg.append("数据 ").append(row.getStr("label")).append(" 有误:").append(validation.getName()).append("\r\n");
                }
            }

            // 再验证正则，最后验证值空间
            Page page = new Page(0, 100);
            while (true) {
                PageResult<Entity> list = db.page(Entity.create(devModel.getCode()), page);
                if(list == null || list.isEmpty()){
                    break;
                }
                for (Entity row: list){
                    for(DevValidation validation:validationList) {
                        if(row.containsKey(validation.getFields()) && row.get(validation.getFields()) != null){
                            String v = row.getStr(validation.getFields());
                            if (validation.getType().equals(DevValidation.TYPE_REG) && !v.matches(validation.getSqls())) {
                                failureNum ++;
                                failureMsg.append("数据 ").append(row.getStr(devModel.getPkField())).append(" 不条件规则:").append(validation.getName()).append("\r\n");
                            }else if (validation.getType().equals(DevValidation.TYPE_META)) {
                                if(!metaMap.containsKey(validation.getSqls())){
                                    BaseMetaSpace msc = new BaseMetaSpace();
                                    msc.setMetaNum(validation.getSqls());
                                    List<BaseMetaSpace> spaceList = baseMetaSpaceService.selectBaseMetaSpaceList(msc);
                                    metaMap.put(validation.getSqls(), "1");
                                    for(BaseMetaSpace space:spaceList){
                                        metaMap.put(validation.getSqls()+"_"+space.getCode(), space.getLabel());
                                    }
                                }
                                if(!metaMap.containsKey(validation.getSqls()+"_"+v)){
                                    failureNum ++;
                                    failureMsg.append("数据 ").append(row.getStr(devModel.getPkField())).append(" 取值无效:").append(validation.getName()).append(" ： ").append(v).append("\r\n");
                                }
                            }
                        }
                    }
                }
                page.setPageNumber(page.getPageNumber()+1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "共 " + failureNum + " 条数据格验证失败，错误如下：");
            return failureMsg.toString();
        }
        else
        {
            return "数据已全部验证通过！";
        }
    }
}
